package com.wxmp.market.zhuli.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wxmp.core.exception.WxErrorException;
import com.wxmp.core.util.StringUtil;
import com.wxmp.market.zhuli.domain.WXQRCode;
import com.wxmp.market.zhuli.mapper.WXQRCodeDao;
import com.wxmp.wxapi.process.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.OutputStream;

@Service("QRCodeService")
@Transactional
public class WXQRCodeServiceImpl {

    @Resource
    WXQRCodeDao wxqrCodeDao;

    @Autowired
    WxApiClient wxApiClient;

    /**
     * 根据活动场景创建二维码
     *
     * @param
     * @param openId
     * @param activityCode
     * @return
     */
    public synchronized WXQRCode getActivityQRCode(String openId, String activityCode, MpAccount account) {
        if (StringUtil.isBlank(openId) || StringUtil.isBlank(activityCode)) {
            //不能为空提示
        }
        //获取场景值
        Integer maxId = wxqrCodeDao.selectMaxId();
        WXQRCode wxqrCode = createQRCode(openId, 2592000, maxId == null ? 1 : maxId + 1, activityCode, account);
        return wxqrCode;
    }

    /**
     * 二维码生成 临时
     *
     * @param
     * @param openId
     * @param expireSecodes 该二维码有效时间，以秒为单位。 最大不超过2592000（即30天），此字段如果不填，则默认有效期为30秒。
     * @param sceneId       临时二维码时为32位非0整型，永久二维码时最大值为100000（目前参数只支持1--100000)
     * @param baseCode
     * @return
     * @throws WxErrorException
     */
    private WXQRCode createQRCode(String openId, Integer expireSecodes, Integer sceneId, String baseCode, MpAccount account) {
        try {
            String qrUrl = "";
            String fileName = String.format("c://gimborn//qrcode//%s-%s.jpg", baseCode, openId);
            if (sceneId != null) {
                String accessToken = WxApiClient.getAccessToken(account);
                String postBody = WxApi.getQrcodeJson(expireSecodes, sceneId);
                JSONObject jsObj = WxApi.httpsRequest(WxApi.getCreateQrcodeUrl(accessToken), HttpMethod.POST, postBody);
                if (jsObj != null) {
                    String ticket = jsObj.getString("ticket");

                    qrUrl = WxApi.getShowQrcodeUrl(ticket);
                    //if (!StringUtils.isBlank(ticket)) {
                    byte[] imgByte = WxApi.httpsRequestByte(WxApi.getShowQrcodeUrl(ticket), HttpMethod.GET);
                    try {
                        OutputStream os = new FileOutputStream(fileName);
                        os.write(imgByte, 0, imgByte.length);
                        os.flush();
                        os.close();
                    } catch (Exception ex) {
                        //异常处理
                    }
                }

                //数据库写入
                WXQRCode qrCode = new WXQRCode();
                qrCode.setBaseCode(baseCode);
                qrCode.setQrCodeUrl(qrUrl);
                qrCode.setQrCreater(openId);
                qrCode.setQrExpireSeconds(expireSecodes);
                qrCode.setQrSceneId(sceneId);
                qrCode.setQrPathName(fileName);
                qrCode.setQrType(1);
                wxqrCodeDao.add(qrCode);
                return qrCode;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
        return null;
    }
}
